package com.wbs.shop.nuby.jsbridge.core;


import com.alibaba.fastjson.JSONObject;
import com.wbs.shop.nuby.utils.Logger;
import com.wbs.shop.nuby.utils.StringUtils;
import com.wbs.shop.nuby.view.listener.IWebView;

import java.lang.reflect.Method;
import java.util.ArrayList;


/**
 * Created by Administrator on 2017/3/1 0001.
 */

public class InjectedUtils {
    public static Object invoke(IWebView webView, Object object, String methodName, JSONObject paramJsonObject, String callbacks) {
        if (object != null && StringUtils.isNotEmpty(methodName)) {
            try {
                ArrayList<Class> paramClass = new ArrayList<>();
                ArrayList<Object> paramObject = new ArrayList<>();
                if (!paramJsonObject.isEmpty()) {
                    paramClass.add(JSONObject.class);
                    paramObject.add(paramJsonObject);
                }
                if (StringUtils.isNotEmpty(callbacks)) {
                    String[] callbacksArr = StringUtils.split(callbacks, ",");
                    for (String callback : callbacksArr) {
                        paramClass.add(JsCallback.class);
                        paramObject.add(new JsCallback(callback, webView));
                    }
                }
                Method declaredMethod = object.getClass().getDeclaredMethod(methodName, paramClass.toArray(new Class[]{}));
                return declaredMethod.invoke(object, paramObject.toArray());
            } catch (Exception e) {
                Logger.e(e);
            }
        }
        return null;
    }
}
